<?php
namespace bdhert\PhpBitfield;

use bdhert\PhpBitfield\exception\InformatsException;

/**
 * 顺序结构
 * Class BitIndex
 * @package bdhert\PhpBitfield
 */
final class BitIndex extends BitANLS implements \Countable,Index,BitString {
    /**
     * 获取顺序列表
     * @return array
     */
    public function get(): array {
        $data = [];
        $this->mapActions(static function ($index, $fields) use(&$data) {
            $data[] = ['index' => $index, 'value' => $fields[0]];
        }, false, true);

        return $data;
    }

    /**
     * 总计记录数
     * @return int
     */
    public function count(): int {
        return $this->head->total;
    }

    /**
     * 获取值
     * @param int $index
     * @return int|null
     */
    public function find(int $index): ?int {
        return $this->getValue($index, 0, true);
    }

    /**
     * 获取索引
     * @param int $value
     * @return int|null
     */
    public function index(int $value): ?int {
        $this->conditions[0] = ['=', $value];
        [$this->page, $this->limit, $this->sort] = [0, 1, SORT_ASC];

        $index = NULL;
        $this->mapActions(static function ($i, $f) use(&$index) {
            $index = $i;
        }, true, true);

        $this->reset(false);
        return $data[0] ?? NULL;
    }

    /**
     * 增加新值
     * @param int $value
     * @return string
     */
    public function insert(int $value): string {
        $this->addValue([$value]);
        $this->initialize($string = $this->string());
        return $string;
    }

    /**
     * 分页
     * @param int $page
     * @param int $limit
     * @return $this|Index
     */
    public function limit(int $page, int $limit = 0): Index {
        empty($limit) && $limit = $this->limit;
        if ($page < 1 || $limit < 1) throw new InformatsException('分页参数错误', 400);

        [$this->page, $this->limit] = [$page, $limit];

        return $this;
    }

    /**
     * 类型检测
     * @return bool
     */
    public function formatCheck(): bool {
        return $this->head->field->total === 1;
    }
}